package icu.zlz.emqx.controller;

import icu.zlz.common.core.constant.MqttConstants;
import icu.zlz.common.core.utils.poi.ExcelUtil;
import icu.zlz.common.core.web.controller.BaseController;
import icu.zlz.common.core.web.domain.AjaxResult;
import icu.zlz.common.core.web.page.TableDataInfo;
import icu.zlz.common.log.annotation.Log;
import icu.zlz.common.log.enums.BusinessType;
import icu.zlz.common.security.annotation.Logical;
import icu.zlz.common.security.annotation.RequiresPermissions;
import icu.zlz.emqx.domain.IotDevices;
import icu.zlz.emqx.domain.PushMsg;
import icu.zlz.emqx.service.IIotDevicesService;
import icu.zlz.emqx.service.impl.EmqxService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 设备管理Controller
 *
 * @author zangs
 * @since 2025-01-02
 */
@RestController
@RequestMapping("/devices")
public class IotDevicesController extends BaseController {
    @Autowired
    private IIotDevicesService iotDevicesService;
    @Autowired
    private EmqxService emqxService;

    @Resource
    private MqttClient mqttClient;
    /**
     * 查询在线用户
     *
     * @param page  页数
     * @param limit 每页条数
     * @param cids  客户端id
     * @return
     */
    @RequiresPermissions("emqx:devices:list")
    @GetMapping("/clients/{page}/{limit}/{cids}")
    public AjaxResult clients(@PathVariable Integer page, @PathVariable Integer limit, @PathVariable("cids") String[] cids) {
        return AjaxResult.success(iotDevicesService.getOnlineClients(emqxService.getClients(page, limit, null, cids, null)));
    }


    @RequiresPermissions("emqx:devices:list")
    @GetMapping("/groupList/{name}")
    public AjaxResult groupList(@PathVariable("name") String name) {
        return AjaxResult.success(iotDevicesService.selectIotGroupList(name));
    }

    @RequiresPermissions(value = {"emqx:devices:add", "emqx:devices:edit"}, logical = Logical.OR)
    @GetMapping("/topicList")
    public AjaxResult topicList() {
        return AjaxResult.success(iotDevicesService.selectIotTopicList());
    }


    /**
     * 查询设备管理列表
     */
    @RequiresPermissions("emqx:devices:list")
    @GetMapping("/list")
    public TableDataInfo list(IotDevices iotDevices) {
        startPage();
        List<IotDevices> list = iotDevicesService.selectIotDevicesList(iotDevices);
        return getDataTable(list);
    }

    /**
     * 导出设备管理列表
     */
    @RequiresPermissions("emqx:devices:export")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IotDevices iotDevices) {
        List<IotDevices> list = iotDevicesService.selectIotDevicesList(iotDevices);
        ExcelUtil<IotDevices> util = new ExcelUtil<IotDevices>(IotDevices.class);
        util.exportExcel(response, list, "设备管理数据");
    }

    /**
     * 获取设备管理详细信息
     */
    @RequiresPermissions("emqx:devices:query")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return success(iotDevicesService.selectIotDevicesByDeviceId(deviceId));
    }

    /**
     * 新增设备管理
     */
    @RequiresPermissions("emqx:devices:add")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotDevices iotDevices) {
        return toAjax(iotDevicesService.insertIotDevices(iotDevices));
    }

    /**
     * 修改设备管理
     */
    @RequiresPermissions("emqx:devices:edit")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IotDevices iotDevices) {
        return toAjax(iotDevicesService.updateIotDevices(iotDevices));
    }

    /**
     * 删除设备管理
     */
    @RequiresPermissions("emqx:devices:remove")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        return toAjax(iotDevicesService.deleteIotDevicesByDeviceIds(deviceIds));
    }

    /**
     * 消息推送
     * @param deviceIds 设备id
     * @param msg 消息
     * @return 结果
     * @throws UnsupportedEncodingException
     * @throws MqttException
     */
    @RequiresPermissions("iot:devices:send")
    @Log(title = "devices", businessType = BusinessType.INSERT)
    @PostMapping("/send/{deviceIds}")
    public AjaxResult send(@PathVariable Long[] deviceIds, @RequestBody PushMsg msg) throws UnsupportedEncodingException, MqttException {
        List<IotDevices> iotDevices = iotDevicesService.selectIotDevicesByDeviceIds(deviceIds);
        for (IotDevices iotDevice : iotDevices) {
            String subscribeTopic = MqttConstants.MQTT_CLIENT_TOPIC + "/" + iotDevice.getUid() + "/" + iotDevice.getDeviceClientId();
            mqttClient.publish(subscribeTopic, msg.getContent().getBytes(MqttConstants.MSG_CODE), msg.getQos(), msg.isRetained());
        }
        return success();
    }
}
